import logging
import requests
import json
import time
from datetime import datetime, timedelta
from offline_calc.handler import OfflineCalculationHandler
from event_rule.cp.op_event_rule import rule_config
from common.es_core.es_interface import es_search_interface
from common.redis.redis import AGENT_REDIS

_LOGGER = logging.getLogger(__name__)


class Command(OfflineCalculationHandler):
    def __init__(self, *args, **kwargs):
        super(Command, self).__init__(*args, **kwargs)
        self.index_list = ['dark3', 'dark4', 'tt', 'zs', 'dark2']
        self.event_config = rule_config.CONFIG
        self.platform_mapper = {
            'dark2': 'dltgjm',
            'dark3': 'dltghj3',
            'dark4': 'dltgdark4',
            'tt': 'dltgtt',
            'zs': 'dltgzs'
        }

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)

    def handle(self, **kwargs):
        res = requests.get('http://api.qt266.com/agent/api/bind_chn_list/')
        bind_chn_pool = json.loads(res.content)['data']['chn']
        today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=1)
        today_end = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
        result = {}
        for index in self.index_list:
            active_chn_list = []
            agent_platform_name = self.platform_mapper[index]
            chn_list = bind_chn_pool[agent_platform_name]
            query_dsl = {
                "query": {
                    "bool": {
                        "filter": [
                            {"terms": {"_event_id": ['recharge', 'withdraw', 'tax', 'register', 'bind', 'bet_order']}},
                            {"terms": {"_chn.keyword": chn_list}},
                            {"range": {"_event_time": {"gte": today_start.timestamp(),
                                                       "lt": today_end.timestamp()}}}
                        ]
                    }
                },
                "aggs": {
                    "__": {
                        "terms": {
                            "field": "_chn.keyword",
                            "size": 10000
                        }
                    }
                }
            }
            res_json = es_search_interface(index, query_dsl)
            for each in res_json['aggregations']['__']['buckets']:
                active_chn_list.append(each['key'])
            query_dsl = {
                "query": {
                    "bool": {
                        "filter": [
                            {"terms": {"_event_id": ['recharge', 'withdraw', 'tax', 'register', 'bind', 'bet_order']}},
                            {"terms": {"_agent_chn.keyword": chn_list}},
                            {"range": {"_event_time": {"gte": today_start.timestamp(),
                                                       "lt": today_end.timestamp()}}}
                        ]
                    }
                },
                "size": 0,
                "aggs": {
                    "__": {
                        "terms": {
                            "field": "_agent_chn.keyword",
                            "size": 10000
                        }
                    }
                }
            }
            res_json = es_search_interface(index, query_dsl)
            for each in res_json['aggregations']['__']['buckets']:
                active_chn_list.append(each['key'])
            result[agent_platform_name] = active_chn_list
        result['timestamp'] = time.time()
        redis_key = 'agent_active_chn'
        AGENT_REDIS.set(redis_key, json.dumps(result))


